require 'cgi/session'


# === リクエスト．
#
# Author:: krdlab
#
class Request
  attr_accessor :url, :cgi, :session, :parts, :action, :data

  def initialize
    @cgi = CGI.new
    @cgi.params.merge!(CGI::parse(@cgi.query_string)) if is_post?
    @session = get_session
    @url = ENV['REQUEST_URI']
    @parts = cgi['command'].split(/\//)
    @action = parts[0]
  end

protected
  def get_session
    begin
      return CGI::Session.new(cgi, {'new_session' => false})
    rescue ArgumentError
      return nil
    end
  end

public
  def new_session
    old = session || get_session
    if not old.nil? then
      old.delete
    end
    session = CGI::Session.new(cgi, {'new_session' => true})
  end

  def is_post?
    return cgi.request_method.upcase == 'POST'
  end

  def get_parameter(key)
    return cgi[key]
  end

  def update_session
    if not session.nil? then
      session.update
    end
  end

  def close_session
    if not session.nil? then
      session.close
    end
  end

  def add_attr(*symbols)
    symbols.each {|symbol|
      self.instance_eval %{
        def #{symbol}
          @#{symbol}
        end
        def #{symbol}=(value)
          @#{symbol} = value
        end
      }
    }
  end
end

